<template>
	<view>
		<!-- 设备获取体重 -->
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	const QNBleApi = require("@/components/peripheral/qnble")
	import { init } from '@/sg/index'
	const {
		Report
	} = require("@/components/peripheral/index")
	// #endif
	export default {
		data() {
			return {
				deviceId: '',
				mac: '',
				age: 30,
				autoStopDiscovery: true,
				gender: "male",
				height: 170,
				isSport: false,
				unit: "kg",

				realTimeWeight: 0,
				bleState: "空闲",
				state: "paused",
				measureData: null,
				score: 0,
				available: false,
				discovering: false,
				connected: false,
				connecting: false,
			}
		},
		created() {
			let options = {};
			options.form =
				'{"measureMethod":"auto","gender":"male","height":170,"age":30,"isSport":false,"unit":"kg","autoStopDiscovery":true}'
			console.log("212212" + options)
			if (options.form) {
				const form = JSON.parse(options.form)
				console.log(form)
				this.age = form.age;
				this.autoStopDiscovery = form.autoStopDiscovery;
				this.gender = form.gender;
				this.height = form.height;
				this.isSport = form.isSport;
				this.measureMethod = form.measureMethod;
				this.unit = form.unit;
				// this.setData({
				// 	...form
				// })
			}

			//初始化蓝牙
			this.bleApi = new QNBleApi()

			this.bleApi.setDeviceEventListener(this);
			this.bleApi.setBleEventListener(this);

			wx.openBluetoothAdapter({
				mode: "peripheral",
				success: res => {
					wx.createBLEPeripheralServer({
						success: res => {
							//设置广播秤的蓝牙服务
							console.log("蓝牙状态变化，设置蓝牙服务")
							this.bleApi.setBleServer(res.server)
						}
					})
				}
			})

		},
		mounted() {
			const {
				autoStopDiscovery
			} = this
			this.bleApi.init({
					appId: "wx3581a642cd0e4a4d",
					secret: "42e4c5d4a8d52e5241b29022a7b9865c",
					autoStopDiscovery,
					logger: this.logger()
				})
				.then(bleEnableState => {
					console.log("当前蓝牙状态", bleEnableState)
					if (bleEnableState)
						this.bleApi.startBleDeviceDiscovery()
				})
		},
		// 组件加载完毕
		updated() {
			// 调用搜索设备
		},
		destroyed() {
			// this.bleApi.stop()
			this.bleApi.stop()
				.then(() => {
					this.connected = false
				})
			init(global.userInfo.userId)
		},
		// onUnload() {
		// 	this.bleApi.stop()
		// 		.then(() => {
		// 			this.connected =false
		// 		})
		// },
		methods: {
			logger: () => {
				const wxlogger = wx.getLogManager && wx.getLogManager({
					level: 0,
				})
				const log = (...params) => {
					console.log(...params)
					wxlogger && wxlogger.log(...params)
				}
				return {
					log
				}
			},
			//事件回调
			restart() {
				this.bleApi.stop()
					.then(() => {
						this.connected = false;
						this.bleApi.startBleDeviceDiscovery()
					})
					.catch((err) => {
						console.log("停止扫描失败", err)
					})
			},

			//下面是蓝牙事件的相关回调
			//开始扫描的回调
			onInitSuccess(bleEnableState) {
				if (bleEnableState) {
					this.updateState("蓝牙可用")
				} else {
					this.updateState("蓝牙不可用")
				}
			},
			onStartDiscoveryDevice() {
				this.updateState("开始扫描")
				this.devices = []
				this.discovering = true
			},

			//结束扫描的回到
			onStopDiscoveryDevice() {
				this.updateState("已停止扫描")
				this.discovering = false
			},
			//回调扫描对象
			onBleDeviceFound(device) {
				const {
					height,
					age,
					gender,
					isSport,
					unit,
					connected,
				} = this
				if (this.connecting || connected) {
					console.log("当前正在连接，不再处理")
					return
				}
				this.connecting = true
				const birthday = new Date()
				birthday.setFullYear(birthday.getFullYear() - age)
				const user = {
					height,
					age,
					gender,
					isSport,
					birthday,
				}
				this.bleApi.createBleConnection(device, {
					user,
					unit,

				})
				// this.bleApi.stopBleDeviceDiscovery()
			},
			/**
			 * 正在进行连接设备，在调用连接设备后，会马上回调
			 */
			onConnecting(device) {
				this.updateState("正在连接")
				this.connecting = true
				this.connected = false
			},
			/**
			 * 	设备已连接成功 会回调设备对象
			 */
			onConnected(device) {
				this.updateState("已连接")
				console.log("设备已连接", device);
				this.connecting = false
				this.connected = true;
				this.state = "running";
				this.device = device
				this.deviceId = device.deviceId; //设备已连接
				this.mac = device.mac; //设备mac
				// device
			},

			onBluetoothEnableChange(bleEnableStatus) {
				if (bleEnableStatus) {
					this.updateState("蓝牙可用，空闲")
					wx.openBluetoothAdapter({
						mode: "peripheral",
						success: res => {
							wx.createBLEPeripheralServer({
								success: res => {
									//设置广播秤的蓝牙服务
									console.log("蓝牙状态变化，设置蓝牙服务")
									this.bleApi.setBleServer(res.server)
								}
							})
						}
					})
				} else {
					this.updateState("蓝牙不可用")
				}
				this.available = bleEnableStatus
			},


			/**
			 * 	设备的服务搜索完成，正常情况下会在 onConnected后面调用
			 */
			onDeviceReady(device) {
				this.updateState("设备已经就绪")
				console.log("设备已就绪", device);
			},

			/**
			 * 蓝牙断开了连接
			 */
			onDisconnected(device) {
				this.updateState("设备连接已断开")
				this.connected = false;
				this.state = "paused";
				this.connecting = false
				this.connecting = false
				this.connected = false
				console.log("设备连接已断开", device);
			},

			//下面是秤端相关事件回调
			onGetUnsteadyWeight(weight) {
				console.log("收到实时数据", weight);
				this.score = weight;
				this.realTimeWeight = weight
				this.connected = true;
				this.state = "running";
			},
			/**
			 * 获取到了实时的稳定测量数据，在连接APP的情况下，进行测量，数据会进入到这个回调
			 * @param {object} scaleData 体脂秤数据
			 */
			onGetScaleData(scaleData) {
				this.updateState("测量完成")
				// 数据返回
				console.log("称重结束", scaleData)
				console.log("发送数据", scaleData)
				// 发送请求保存到数据库中
				// let scaleData1 = scaleData;

				this.$emit('balanceData', {
					equipmentData: JSON.stringify(scaleData),
					deviceId: this.deviceId,
					mac: this.mac
				})
				//  delete scaleData1.device;
				// let measureInfo = scaleData.user;

				// wx.request({
				// 	url: 'http://192.168.100.9:18602/equipment/measureResult', //仅为示例，并非真实的接口地址
				// 	method: "POST",
				// 	header: {
				// 		"Content-Type": "application/x-www-form-urlencoded",
				// 		"Authorization": 'eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjEsInN1YiI6InVzZXIiLCJmb3VuZGVyIjpudWxsLCJyb2xlcyI6WyJTVVBFUl9BRE1JTiJdLCJleHAiOjE2MTU3ODAwNTksInV1aWQiOm51bGwsInNob3BVaWQiOm51bGwsInVzZXJuYW1lIjoiYWRtaW4ifQ.lntgpE9jPgUQzTK_jr_e0In_76tltx9MqzUQ4uEajRjwQ-my7fH8Ye9DtRRs0aScxshmNDPh6NwuvX3H8VvS-w'
				// 	},
				// 	data: {
				// 		measureResult: JSON.stringify(scaleData1),
				// 		measureInfo: JSON.stringify(measureInfo),
				// 		equipmentId: 1
				// 	},
				// 	success(res) {
				// 		console.log(res.data)
				// 	},
				// 	error(e) {
				// 		console.log(e)
				// 	}
				// })

				// const report = new Report(scaleData)
				// this.realTimeWeight = scaleData.weight;
				// this.state = "paused";
				// this.score = scaleData.score.toString();
				// this.measureData = report
			},

			onStartMeasureFat() {
				console.log("开始测量体脂")
			},

			onStartMeasureHeart() {
				console.log("开始测量心率")
			},
			/**
			 * 发送请求计算测量数据失败
			 * @param {*} err 
			 */
			onFetchScaleDataFail(err) {
				console.log("计算数据失败", err)
			},

			updateState(state) {
				this.bleState = state
			},

			testRequest() {
				const weight = 60
				const {
					height,
					age,
					gender,
					isSport
				} = this.data
				const birthday = new Date()
				birthday.setFullYear(birthday.getFullYear() - age)
				const user = {
					height,
					age,
					gender,
					isSport,
					birthday,
				}

				this.bleApi.fakeRequest(weight, user)
					.then((measureData) => {
						const report = new Report(measureData)
						console.log("报告数据", report)
						this.measureData = report;
						this.score = measureData.score.toString();
					})

			},
		}
	}
</script>

<style>
</style>
